//
//  HJDResigesViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/6/1.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDResigesViewController.h"
#import "AFNetworking.h"
#import "HJDDatePickerView.h"
#import "HJDLoginViewController.h"
#import <CommonCrypto/CommonDigest.h>

#define HJDHorVM 46


@interface HJDResigesViewController ()<UWDatePickerViewDelegate>
{
    HJDDatePickerView * _pickerView;
}
@property (nonatomic,strong) UIButton *btn ;
@property (nonatomic,assign) int  second;
@property (nonatomic,strong) NSTimer * timer;

@property (nonatomic,strong) UITextField  *phoneField;
@property (nonatomic,strong) UITextField *mesTestText;
@property (nonatomic,strong) UITextField  *passwordtextField;
@property (nonatomic,strong) UITextField  *passwordSecondtextField;

@property (nonatomic,strong) UIButton * timeBtn;


@property (nonatomic,strong) UILabel * timeLbl ;



@end

@implementation HJDResigesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];

    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpTextFiled];
    self.second = 60;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(popToPre) image:@"︿" HighImage:nil];
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
}

//隐藏键盘
-(void)viewTapped:(UITapGestureRecognizer*)tap
{
    
    [self.view endEditing:YES];
    
}

//返回
-(void)popToPre
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)setUpTextFiled{
    CGFloat phoneX = HJDHorVM;
    CGFloat phoneY = 81;
    CGFloat phoneW = HJDWidth - 46*2;
    CGFloat phoneH = 40;
    self.phoneField = [[UITextField alloc]initWithFrame:CGRectMake(phoneX, phoneY, phoneW, phoneH)];
    self.phoneField.placeholder = @"输入手机号";
//    一次性清空
    self.phoneField.clearButtonMode = UITextFieldViewModeAlways;
    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
    [self.phoneField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.phoneField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    
    [self.view addSubview:self.phoneField];
    
    //    横线
    CGFloat viewX = HJDHorVM ;
    CGFloat viewY = CGRectGetMaxY(self.phoneField.frame);
    CGFloat viewW = phoneW;
    CGFloat viewH = 1;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
    view.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:view];
    
    
    CGFloat timeBtnX = HJDHorVM;
    CGFloat timeBtnY = CGRectGetMaxY(view.frame) + HJDVerticalMargin;
    CGFloat timeBtnW = HJDWidth;
    CGFloat timeBtnH = 40;
    self.timeBtn = [[UIButton alloc]initWithFrame:CGRectMake(timeBtnX, timeBtnY, timeBtnW, timeBtnH)];
    [self.timeBtn addTarget:self action:@selector(timeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.timeBtn setTitle:@"末次经期" forState:UIControlStateNormal];
    [self.timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, HJDWidth - 80)];
    [self.timeBtn setTitleColor:[UIColor getColorWithHexNumber:@"323232"] forState:UIControlStateNormal];
    [self.view addSubview:self.timeBtn];
    
    CGFloat timeLblX = 150 ;
    CGFloat timeLblY = timeBtnY;
    CGFloat timeLblW = 150;
    CGFloat timeLblH = 40;
    self.timeLbl = [[UILabel alloc]initWithFrame:CGRectMake(timeLblX, timeLblY, timeLblW, timeLblH)];
    
    self.timeLbl.text = @"";
    self.timeLbl.textColor = [UIColor grayColor];
    [self.view addSubview:self.timeLbl];
    
    CGFloat viewmX = HJDHorVM ;
    CGFloat viewmY = CGRectGetMaxY(self.timeLbl.frame);
    CGFloat viewmW = phoneW;
    CGFloat viewmH = 1;
    UIView *viewm = [[UIView alloc]initWithFrame:CGRectMake(viewmX, viewmY, viewmW, viewmH)];
    viewm.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:viewm];
    
    
    
    CGFloat mesTestTextX = HJDHorVM;
    CGFloat mesTestTextY = CGRectGetMaxY(viewm.frame) + HJDVerticalMargin;
    CGFloat mesTestTextW = phoneW - 120;
    CGFloat mesTestTextH = phoneH;
    self.mesTestText = [[UITextField alloc]initWithFrame:CGRectMake(mesTestTextX, mesTestTextY, mesTestTextW, mesTestTextH)];
     self.mesTestText .keyboardType = UIKeyboardTypeNumberPad;
    self.mesTestText.clearButtonMode = UITextFieldViewModeAlways;
    self.mesTestText .placeholder = @"输入验证码";
    [self.mesTestText  setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.mesTestText  setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
   
    [self.view addSubview:self.mesTestText ];
    
    CGFloat btnX = CGRectGetMaxX(self.mesTestText.frame);
    CGFloat btnY = mesTestTextY;
    CGFloat btnW = 120;
    CGFloat btnH = mesTestTextH;
    
    self.btn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
    [self.btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.btn setRadius:10 borderWith:0 borderColor:nil];
    self.btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.btn setBackgroundColor:[UIColor getColorWithHexNumber:@"FF9EAC"]];
    [self.btn addTarget:self action:@selector(mesTestBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
    //    横线
    CGFloat mesTestviewX = HJDHorVM ;
    CGFloat mesTestviewY = CGRectGetMaxY(self.mesTestText .frame);
    CGFloat mesTestviewW = mesTestTextW ;
    CGFloat mesTestviewH = 1;
    UIView *mesTestview = [[UIView alloc]initWithFrame:CGRectMake(mesTestviewX, mesTestviewY, mesTestviewW, mesTestviewH)];
    mesTestview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:mesTestview];

    
    CGFloat passwordX = HJDHorVM ;
    CGFloat passwordY = CGRectGetMaxY(self.btn.frame) + HJDVerticalMargin;
    CGFloat passwordW = phoneW;
    CGFloat passwordH = phoneH;
    self.passwordtextField = [[UITextField alloc]initWithFrame:CGRectMake(passwordX, passwordY,passwordW, passwordH)];
    self.passwordtextField.secureTextEntry = YES;
    self.passwordtextField.clearButtonMode = UITextFieldViewModeAlways;
    self.passwordtextField.placeholder = @"设置密码：";
    [self.passwordtextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];

    [self.passwordtextField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordtextField addTarget:self action:@selector(textPassChange) forControlEvents:UIControlEventEditingChanged];
    
    [self.view addSubview:self.passwordtextField];
    //    横线
    CGFloat passwordviewX = HJDHorVM;
    CGFloat passwordviewY = CGRectGetMaxY(self.passwordtextField.frame);
    CGFloat passwordviewW = phoneW;
    CGFloat passwordviewH = 1;
    UIView *passwordview = [[UIView alloc]initWithFrame:CGRectMake(passwordviewX, passwordviewY, passwordviewW, passwordviewH)];
    passwordview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:passwordview];
    
   
    
    CGFloat passwordSecondX = HJDHorVM;
    CGFloat passwordSecondY = CGRectGetMaxY(passwordview.frame) + HJDVerticalMargin;
    CGFloat passwordSecondW = phoneW;
    CGFloat passwordSecondH = phoneH;
   self.passwordSecondtextField = [[UITextField alloc]initWithFrame:CGRectMake(passwordSecondX, passwordSecondY,passwordSecondW, passwordSecondH)];
    self.passwordSecondtextField.clearButtonMode = UITextFieldViewModeAlways;
    self.passwordSecondtextField.secureTextEntry = YES;
    self.passwordSecondtextField.placeholder = @"确认密码：";
    [self.passwordSecondtextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    
    [self.passwordSecondtextField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordtextField addTarget:self action:@selector(textPassSChange) forControlEvents:UIControlEventEditingChanged];
    
    [self.view addSubview:self.passwordSecondtextField];
    //    横线
    CGFloat passwordSecondviewX = HJDHorVM ;
    CGFloat passwordSecondviewY = CGRectGetMaxY(self.passwordSecondtextField.frame);
    CGFloat passwordSecondviewW = phoneW;
    CGFloat passwordSecondviewH = 1;
    UIView *passwordSecondview = [[UIView alloc]initWithFrame:CGRectMake(passwordSecondviewX, passwordSecondviewY, passwordSecondviewW, passwordSecondviewH)];
    passwordSecondview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:passwordSecondview];
    
    
    
    CGFloat loginbtnX = HJDHorVM;
    CGFloat loginbtnY = CGRectGetMaxY(passwordSecondview.frame) + 38;
    CGFloat loginbtnW = phoneW;
    CGFloat loginbtnH = 50;
    UIButton *loginbtn = [[UIButton alloc]initWithFrame:CGRectMake(loginbtnX, loginbtnY, loginbtnW, loginbtnH)];
    [loginbtn setTitle:@"提交" forState:UIControlStateNormal];
    loginbtn.titleLabel.font = [UIFont systemFontOfSize:19];
    [loginbtn setRadius:10 borderWith:0 borderColor:nil];
    [loginbtn setBackgroundColor:[UIColor getColorWithHexNumber:@"5CC6AC"]];
    [loginbtn addTarget:self action:@selector(loginbtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginbtn];
    
    
}

-(void)textPassChange
{
    NSRange _range = [self.passwordtextField.text rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        [MBProgressHUD showError:@"不可输入空格，请重新输入"];
        
    }

}

-(void)textPassSChange
{
    NSRange _range = [self.passwordSecondtextField.text rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        [MBProgressHUD showError:@"不可输入空格，请重新输入"];
        
    }
}

-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    return [hash lowercaseString];
}



-(void)timeBtnClick{
    [self setupDateView:DateTypeOfStart];
    
}

- (void)setupDateView:(DateType)type {
    
    _pickerView = [HJDDatePickerView instanceDatePickerView];
    _pickerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [_pickerView setBackgroundColor:[UIColor greenColor]];
    _pickerView.delegate = self;
    _pickerView.type = type;
    [self.view addSubview:_pickerView];
    
}

- (void)getSelectDate:(NSString *)date type:(DateType)type {
    self.timeLbl.textColor = [UIColor getColorWithHexNumber:@"FE93A2"];
    switch (type) {
        case DateTypeOfStart:
            // TODO 日期确定选择
            break;
            
        case DateTypeOfEnd:
            // TODO 日期取消选择
            break;
        default:
            break;
    }
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60*14 sinceDate:[NSDate date]];//前7天
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:lastDay];
    int ci;
    NSComparisonResult result = [strDate compare:date];
    
    switch (result)
    {
            //date比self.date大
        case NSOrderedAscending:
           
            [MBProgressHUD showError:@"时间太早 可以选择14天以前的哦"];
            ci=1; break;
            //date比self.date小
        case NSOrderedDescending:
            //
            self.timeLbl.text = date;
            
            ci=-1; break;
            //date=self.date
        case NSOrderedSame:
            self.timeLbl.text = date;
            ci=0; break;
        default:
            break;
    }
}



//获取验证码按钮点击事件
-(void)mesTestBtnClick
{
    
//    
   NSString *phone = @"^1+[34578]+\\d{9}";
    NSPredicate *pr = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
    

    
    if ([pr evaluateWithObject:self.phoneField.text ]) {
    
        if (self.timeLbl.text.length !=0) {
                               
            NSString *url = @"/app/smsSend.do";
            NSString *path = [Hurl stringByAppendingString:url];
            
            AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"phone"] = self.phoneField.text;
            params[@"type"] = @"true";
            [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *infoDic = (NSDictionary*)responseObject;
                NSString *successfolStr = infoDic[@"resultCode"];
//                NSLog(@"%@",successfolStr);
                
                if ([successfolStr integerValue] == 004) {
                    [MBProgressHUD showSuccess:@"此号已注册"];
                    
                }else{
                    [self sendVerificationCode];
                    [MBProgressHUD showSuccess:@"验证码已发送"];
                }
                
//                HJDLog(@"%@",responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [MBProgressHUD showError:@"发送失败"];
                HJDLog(@"%@",error);
            }];
            
        }else{
            [MBProgressHUD showError:@"末次月经为空,请选择时间"];
    }

    }else{
    [MBProgressHUD showError:@"请输入正确的手机号"];
    }
    
}
//提交
-(void)loginbtnClick
{
    if (self.mesTestText.text.length >0 ) {
        if (self.mesTestText.text.length == 6) {
//            if (self.timeLbl.text.length ==0) {
            NSLog(@"self.timeLbl%@",self.timeLbl.text);
            NSRange _range = [self.passwordtextField.text rangeOfString:@" "];
            if (_range.location == NSNotFound) {
                NSRange _range = [self.passwordSecondtextField.text rangeOfString:@" "];
                if (_range.location == NSNotFound) {
                    

        
        NSString *url = @"/app/register.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        
        NSString *strr = [self md5:self.passwordtextField.text];
        NSLog(@"%@",strr);

        
        params[@"phone"] = self.phoneField.text;
        params[@"password"] = strr;
        params[@"code"] = self.mesTestText.text;
        params[@"pregnancy"] = self.timeLbl.text;
        
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *infoDic = (NSDictionary*)responseObject;
            NSString *successfolStr = infoDic[@"resultCode"];

            
           
                if ([self.passwordtextField.text isEqualToString:self.passwordSecondtextField.text]) {
                    
                    if ([successfolStr integerValue] == 005) {
                          [MBProgressHUD showError:@"验证码失效或错误"];
                    }else {
                        [MBProgressHUD showSuccess:@"注册成功"];
                        HJDLog(@"%@",responseObject);
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                   
                }else{
                    [MBProgressHUD showError:@"两次密码不一致"];
                }

            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"注册失败"];
            HJDLog(@"%@",error);
        }];

                }else{
                    [MBProgressHUD showError:@"确认密码有空格，请重新输入"];
                }
            }else{
                [MBProgressHUD showError:@"设置密码有空格，请重新输入"];
            }

        }else{
            [MBProgressHUD showError:@"验证码长度不对"];
        }
    }else{
        [MBProgressHUD showError:@"验证码不能为空"];
    }
    
    

    
    HJDLog(@"提交");
}

-(void)changeMin
{
    if (self.second == 0) {
        
        [self.btn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        self.btn.enabled = YES;
        self.btn.hidden = NO;
        [self.timer invalidate];
        self.second = 60;
        return;
    }
    
    self.btn.enabled = NO;
    [self.btn setTitle:[NSString stringWithFormat:@"%d s",self.second] forState:UIControlStateNormal];
    self.second --;
    
}
- (void)sendVerificationCode
{
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeMin)  userInfo:nil repeats:YES];
  }




@end
